package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zhangmeng
 * @description 用户服务实现类
 * @date 2019/9/6
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        //先查基本信息
        User user = userDao.selectByUsername(username);
        if (null == user) {
            //用户不存在
            return null;
        }
        //根据用户ID查角色信息
        List<Role> roles = roleDao.selectByUserId(user.getId());
        for (Role role : roles) {
            //根据角色ID查权限信息
            List<Permission> permissions = permissionDao.selectByRoleId(role.getId());
            role.getPermissions().addAll(permissions);
        }
        user.getRoles().addAll(roles);
        return user;
    }

    @Override
    public PageResult userFindPage(QueryPageBean queryPageBean) {
        log.info("[用户管理-分页查询]data：{}",queryPageBean);
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        Page<User>users=userDao.userFindPage(queryPageBean.getQueryString());

        return new PageResult(users.getTotal(),users.getResult());
    }

    @Transactional
    @Override
    public void add(User user, Role roles) {
        log.info("[用户管理-添加]data：{},roles:{}",user,roles);

        userDao.insert(user);
        roleDao.insertRoles(roles);

    }


    @Override
    public User findById(Integer id) {
        log.info("[用户管理-编辑]data：{}",id);
        return userDao.selectUserById(id);
    }
    @Transactional
    @Override
    public void edit(User user,Integer[] roleIds) {
        log.info("[用户管理-编辑2]data:{},roles:{}",user.getId(),roleIds);
        userDao.update(user);
        for (Integer roleId : roleIds) {
            roleDao.updateRoles(user.getId(),roleId);
        }

        }


    @Override
    public void delete(Integer id) {
        log.info("【用户管理-删除用户】data：{}",id);
        userDao.delete(id);
    }

    @Override
    public List<Role> findAllRole() {
        log.info("[用户管理-角色列表回显]id:{}");
        return roleDao.findAllRole();

    }




}
